package com.wang.web;

import com.wang.pojo.HomeCost;
import com.wang.pojo.Page;
import com.wang.pojo.User;
import com.wang.service.UserService;
import com.wang.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;


@WebServlet("/manager/userServlet")
public class UserServlet extends HttpServlet {


    private UserService userService = new UserService();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        String action = request.getParameter("action");
        if ("login".equals(action)) {
            login(request, response);
        } else if ("regist".equals(action)) {
            regist(request, response);
        } else if ("logout".equals(action)) {
            logout(request, response);
        } else if ("info".equals(action)) {
            info(request, response);
        } else if ("uploadFace".equals(action)) {
            uploadFace(request, response);
        } else if ("updateInfo".equals(action)) {
            updateInfo(request, response);
        } else if ("page".equals(action)) {
            page(request, response);
        } else if ("delete".equals(action)) {
            delete(request, response);
        } else if ("updatePassWord".equals(action)) {
            updatePassWord(request, response);
        }
    }

    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取验证码正确值
        String value = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //清除session中的验证码键值对
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);


        String username = req.getParameter("username");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        //加密密码
        password = WebUtils.md5(password);
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        if (value != null && value.equalsIgnoreCase(code)) {
            //用户名已存在
            if (userService.existsUsername(username)) {
                System.out.println("用户名已存在");
                req.setAttribute("regist_msg", "用户名已存在");
                req.setAttribute("username", username);
                req.setAttribute("name", name);
                req.setAttribute("email", email);
                req.getRequestDispatcher("/index.jsp").forward(req, resp);
            } else if (userService.existsName(name)) {
                System.out.println("昵称已存在");
                req.setAttribute("regist_msg", "昵称已存在");
                req.setAttribute("username", username);
                req.setAttribute("name", name);
                req.setAttribute("email", email);
                req.getRequestDispatcher("/index.jsp").forward(req, resp);
            } else {
                //注册成功
                User registUser = userService.registUser(new User(null, username, name, password, email, 2, "/img/noface.jpg"));
                req.getSession().setAttribute("user", registUser);
                resp.sendRedirect(req.getContextPath() + "/manager/homeCostServlet?action=page&pageSize=4&pageNo=1");
            }
        } else {
            System.out.println("验证码错误");
            req.setAttribute("regist_msg", "验证码错误");
            req.setAttribute("name", name);
            req.setAttribute("username", username);
            req.setAttribute("email", email);
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
        }
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        password = WebUtils.md5(password);
        System.out.println(password);
        User loginUser = userService.login(new User(username, password));

        if (loginUser != null) {
            //保存用户登录的信息
            req.getSession().setAttribute("user", loginUser);
            resp.sendRedirect(req.getContextPath() + "/manager/homeCostServlet?action=page&pageSize=4&pageNo=1");
        } else if (!userService.existsUsername(username)) {
            req.setAttribute("login_msg", "用户名不存在!");
            req.setAttribute("username", username);
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
        } else {
            req.setAttribute("login_msg", "密码错误!");
            req.setAttribute("username", username);

            req.getRequestDispatcher("/index.jsp").forward(req, resp);
        }
    }

    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath()); //重定向回首页

    }


    protected void info(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("user_id"), 0);
        System.out.println(id);
        User user = userService.getUserById(id);
        req.setAttribute("user", user);
        System.out.println(user);
        req.getRequestDispatcher("/pages/user_info.jsp").forward(req, resp);
    }

    protected void uploadFace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        sfu.setHeaderEncoding("UTF-8");
        String relpath = "/img";
        String path = req.getRealPath(relpath);
        String fn = null;
        try {
            List<FileItem> fileItems = sfu.parseRequest(req);
            for (FileItem fi : fileItems) {
                if (fi.isFormField()) { //文字
                    System.out.println("表单值为：" + fi.getString());
                } else {
                    //文件
                    //获取图片后缀名
                    String format = fi.getName().substring(fi.getName().indexOf("."), fi.getName().length());
                    //图片命名
                    fn = UUID.randomUUID().toString().replaceAll("-", "") + format;
                    System.out.println("文件名是：" + fn);
                    fi.write(new File(path, fn));


                    //更新用户头像路径
                    int user_id = WebUtils.parseInt(req.getParameter("user_id"), 0);
                    //如果原头像不是默认头像，则先删掉
                    File file = new File(req.getRealPath(userService.getUserById(user_id).getFace_path()));
                    if (!"noface.jpg".equals(file.getName()) && !"1.jpg".equals(file.getName())) {
                        file.delete();
                    }
                    //更新头像路径
                    User user = userService.updateUserFace(user_id, ("/img/" + fn));
                    //如果改的是自己的头像，那么更新session域中的参数
                    if (user_id == ((User) req.getSession().getAttribute("user")).getId())
                        req.getSession().setAttribute("user", user);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void updateInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int id = WebUtils.parseInt(req.getParameter("user_id"), 0);
        String username = req.getParameter("username");
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        int newPrivilege = WebUtils.parseInt(req.getParameter("privilege"), 2);
        User user = userService.getUserById(id);
        if (((User) req.getSession().getAttribute("user")).getPrivilege() != 0) {
            //如果当前登录的不是超级管理员，阻止修改权限
            newPrivilege = user.getPrivilege();
        }
        //超级管理员有且只有一个，这个用户的id为1，解决部分漏洞
        if (id == 1) newPrivilege = 0;
        else if (newPrivilege == 0) {
            //如果其他用户想要变成超级管理员,阻止修改权限
            newPrivilege = user.getPrivilege();
        }

        //构造新的user
        User newUser = new User(id, username, name, user.getPassword(), email, newPrivilege, user.getFace_path());
        if (!user.getUserName().equals(username) && userService.existsUsername(username)) {
            System.out.println("用户名已存在");
            resp.sendRedirect(req.getContextPath() + "/manager/userServlet?action=info&msg=1&user_id=" + id);
        } else if (!user.getName().equals(name) && userService.existsName(name)) {
            System.out.println("昵称已存在");
            resp.sendRedirect(req.getContextPath() + "/manager/userServlet?action=info&msg=2&user_id=" + id);
        } else {
            //修改成功
            userService.updateUser(newUser);
            //如果改的是自己的信息，则修改session域参数
            if (id == ((User) req.getSession().getAttribute("user")).getId()) {
                req.getSession().setAttribute("user", newUser);
            }
            resp.sendRedirect(req.getContextPath() + "/manager/userServlet?action=info&msg=0&user_id=" + id);
        }
    }

    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);

        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);

        User user = (User) req.getSession().getAttribute("user");
        if (user == null) {
            //没登录就访问
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        } else {
            Page<User> page = userService.page(pageNo, pageSize, user);

            page.setPageUrl(req.getContextPath() + "/manager/userServlet?action=page");

            req.setAttribute("page", page);
            req.getSession().setAttribute("page", page);

            req.getRequestDispatcher("/pages/user_manager.jsp").forward(req, resp);
        }
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int id = WebUtils.parseInt(req.getParameter("id"), 0);

        userService.deleteUserById(id);

        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), 4);
        resp.sendRedirect(req.getContextPath() + "/manager/userServlet?action=page&pageNo=" + pageNo + "&pageSize=" + pageSize);
    }

    protected void updatePassWord(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int user_id = WebUtils.parseInt(req.getParameter("user_id"), 0);

        String original_pw = req.getParameter("original-password");
        original_pw = WebUtils.md5(original_pw);
        User user = userService.getUserById(user_id);

        String new_pw = req.getParameter("new-password");
        new_pw = WebUtils.md5(new_pw);
        //如果改的是自己的才需要校验原密码
        if (((User)req.getSession().getAttribute("user")).getId()==user_id&&!user.getPassword().equals(original_pw)) {
            resp.sendRedirect(req.getContextPath() + "/pages/update_password.jsp?msg=1&user_id=" + user_id);
        } else {
            userService.updateUser(new User(user.getId(), user.getUserName(), user.getName(), new_pw,
                    user.getEmail(), user.getPrivilege(), user.getFace_path()));
            resp.sendRedirect(req.getContextPath() + "/pages/update_password.jsp?msg=0&user_id=" + user_id);
        }

    }

}
